package com.derbysoft.ota.application.translator.rq;

import javax.annotation.Nullable;

import com.derbysoft.modules.eip.translator.Translator;
import com.derbysoft.remote.share.LanguageType;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.googlecode.functionalcollections.FunctionalIterables;
import com.googlecode.functionalcollections.Injector;

public class LanguageTypeTranslator implements Translator<String, LanguageType> {

    public static BiMap<String, LanguageType> ota2switch = HashBiMap.create();
    public static final String EN_US = "en-us";
    public static final String ZH_CN = "zh-cn";

    static {
        initialize();
    }

    private static void initialize() {
        ota2switch.put(EN_US, LanguageType.EN_US);
        ota2switch.put(ZH_CN, LanguageType.ZH_CN);
    }

    private static String errorMessage(String otaLanguage) {
        return FunctionalIterables.make(ota2switch.keySet()).inject(
                new StringBuilder("Unsupported language [ " + otaLanguage + "], supported languages are [ "),
                new Injector<StringBuilder, String>() {
                    public StringBuilder apply(StringBuilder memo, @Nullable String input) {
                        return memo.append(input).append(" ");
                    }
                }
        ).append("]").toString();
    }


    @Override
    public LanguageType translate(String otaLanguage) {
        LanguageType language = ota2switch.get(otaLanguage.toLowerCase());
        if (language == null) {
            throw new IllegalArgumentException(errorMessage(otaLanguage));
        }
        return language;
    }
}
